<template>
    <div class="category">
        <dl class="m-categroy">
            <dt>按拼音首字母选择:</dt>
            <dd v-for="(item, index) in list" :key="index">
                <a :href="'#city-' + item">{{ item }}</a>
            </dd>
        </dl>
        <dl class="m-categroy-section" v-for="(item, index) in cityGroup" :key="index" :id="'city-' + index">
            <dt>{{ index }}</dt>
            <dd>
                <span v-for="(city, i) in item" :key="city.id" @click="changeCity(city)"> {{ city.name }}</span>
            </dd>
        </dl>
    </div>
</template>

<script>
import api from '@/api/index.js'
export default {
  name: 'category',
  data () {
    return {
      list: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
      cityList: [],
      cityGroup: {}
    }
  },
  created () {
    api.getCityList().then(res => {
      const obj = {}
      res.data.data.forEach((item, index) => {
        if (!obj[item.firstChar.toUpperCase()]) {
          obj[item.firstChar.toUpperCase()] = []
        }
        obj[item.firstChar.toUpperCase()].push(item)
      })
      console.log(obj)
      this.cityGroup = obj
    })

    // var data = [{
    //     "id": 59,
    //     "name": "阿门",
    //     "pinyin": "amen",
    //     "acronym": "am",
    //     "rank": "A",
    //     "firstChar": "a"
    // }, {
    //     "id": 1,
    //     "name": "北京",
    //     "pinyin": "changsha",
    //     "acronym": "cd",
    //     "rank": "B",
    //     "firstChar": "b"
    // }, {
    //     "id": 10,
    //     "name": "长沙",
    //     "pinyin": "changsha",
    //     "acronym": "cs",
    //     "rank": "C",
    //     "firstChar": "c"
    // }, {
    //     "id": 59,
    //     "name": "衡阳",
    //     "pinyin": "changsha",
    //     "acronym": "hy",
    //     "rank": "D",
    //     "firstChar": "d"
    // }, {
    //     "id": 56,
    //     "name": "鄂州",
    //     "pinyin": "ezhou",
    //     "acronym": "ezhou",
    //     "rank": "E",
    //     "firstChar": "e"
    // }]
  },
  methods: {
    changeCity (city) {
      this.$store.dispatch('setPosition', city)
      this.$router.push({ name: 'index' })
    }
  }
}
</script>

<style lang="scss">
@import '@/assets/css/changecity/categroy.scss'
</style>
